<script>
import Vue from "vue";
import { maintainApi, updateApi, userInfoApi } from "./api/index.js";
import { appUpdate } from "./utility/download.js";
import { ifLoginFun } from "./utility/weChatLogin.js";
import { getUserRing } from "@/utility/business.js";
import SqLiteLog from "@/js_sdk/sqLite/log.js";
import SqLiteData from "@/js_sdk/sqLite/data.js";
import SqLiteAnaData from "@/js_sdk/sqLite/analysis.js";

export default {
	data() {
		return {
			g_wakelock: null,

			need2Tip: {
				gps: true,
				bluetooth: true,
				user: true,
			},
		};
	},
	onLaunch: () => {
		try {
			
			SqLiteLog.openSqLite();

			setTimeout(() => {
				SqLiteData.openSqLite();
			}, 500);

			setTimeout(() => {
				SqLiteAnaData.openSqLite();
			}, 1000);
		} catch (error) {
			
		}

		// #ifdef APP-PLUS
		if (uni.getSystemInfoSync().platform === "ios" && !plus.runtime.isAgreePrivacy()) {
			uni.reLaunch({
				url: "pages/privacyDlg/privacyDlg",
			});
			return;
		}
		const updateMaintenance = async function () {
			try {
				const updateRes = await appUpdate();
				console.log("updateRes", updateRes);
				if (updateRes && !updateRes.data.isNew) {
					// 有更新就跳转更新页面
					uni.reLaunch({
						url: "/pages/updateMaintenance/update",
					});
					return;
				}

				//判断是否有token
				if (uni.getStorageSync("userToken")) {
					//获取用户信息
					const resUserinfo = await userInfoApi();
					this.$store.commit("setUserInfo", resUserinfo.data);
				}

				// 消息推送
				// handleMessage()
			} catch (e) {
				//TODO handle the exception
			}
		};
		//执行函数
		updateMaintenance();

		const jump = (url) => {
			if (!url) return;
			if (url.substr(0, 4) == "http") {
				const token = uni.getStorageInfoSync("collectionToken");
				let link = "";
				if (url.indexOf("http://game.relaverse.cn") > -1) {
					link = `${link}?acctoken=${token}`;
				} else {
					link = `${url.split("#")[0]}?token=${token}#${url.split("#")[1]}`;
				}
				uni.navigateTo({
					url: `/pages/collection/otherPage?url=${encodeURIComponent(link)}`,
				});
			} else {
				uni.navigateTo({
					url: url,
				});
			}
		};
		const isObject = (payload) => {
			switch (typeof payload) {
				case "object":
					payload.payload ? jump(payload.payload) : "";
					break;
				case "string":
					jump(payload);
					break;
				default:
					break;
			}
		};
		// 被注释
		const handleMessage = () => {
			// 通知消息：ios在线
			plus.push.addEventListener("receive", (msg) => {
				console.log("receive:", msg);
				if (msg.type == "receive") {
					// 这里判断触发的来源，否则一直推送。本地创建的消息没有"type字段
					if (uni.getSystemInfoSync().osName === "ios" && msg.content && msg.title) {
						plus.push.createMessage(msg.content, msg.payload, { title: msg.title, cover: false });
					}
				}
			});
			//对于安卓的在线和离线消息以及IOS的离线消息都是走的click监听事件。
			plus.push.addEventListener("click", (msg) => {
				console.log("click:", msg);
				isObject(msg.payload);
			});
		};
		handleMessage();
		// #endif

		uni.onTabBarMidButtonTap((result) => {
			console.log("点击了中间按钮, onTabBarMidButtonTap", result);
			uni.navigateTo({
				url: "/pages/market/index",
			});
		});
	},
	async mounted() {
		this.$store.dispatch("bleManage/listenBluetoothAdapterStateChange");
		this.$store.dispatch("bleManage/listenBluetoothCharacteristicValueChange");
		this.$store.dispatch("bleManage/listenBluetoothDeviceFoundChange");
		this.$store.dispatch("bleManage/listenBluetoothConnectionStateChange");
		this.$store.dispatch("ringDataManage/addNotify");

		const userRing = await getUserRing();
		if (typeof userRing === "object" && userRing.mac) {
			console.log("》》》》》》》》》》》》》》》》==============开始判断蓝牙权限======================== ");
			this.checkPerm();
		}

		// this.$store.commit(
		// 	"setUserToken",
		// 	"Bearer " +
		// 		// "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiIxNjkwNyIsImlkIjoiMTY5MDcifQ.vMB3mQA7ejJtAP6Z2PTpNYBw9nJtlB5RzhqsCOVB5pg" // 客户1
		// 		// "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiI0MTY0IiwiaWQiOiI0MTY0In0.xq9QGoq81H_ge3Q_ba9Y4DNBFvdnepDOLqfsSUFlVvM" // 客户2
		// 		// "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjEwIiwiaXNzIjoiMTAifQ.db5AaAVFcvuSkiGFvS8V-_i1kyoeq5yX8uVAS8-954g" // hrf
		// 		"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiI4MjMyNTQiLCJpZCI6IjgyMzI1NCJ9.ttrKI_Cc6AOHWZVBWF5z5PnR8km7JZSpFxcTy6y-bk4" // wyd
		// 	// "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjgyMzI5NiIsImlzcyI6IjgyMzI5NiJ9.H3Um7nvPckk1eaLNqjsVaou-6ogjcOe2zvP8SnbNqA0" //jerry 823296
		// );

		// console.log("📃是什么呢：：：： =》》》", plus.io.convertLocalFileSystemURL("downloads/data.db"));
	},
	onShow: function () {
		console.log("App Show");
		// #ifdef APP-PLUS
		Vue.prototype.$hideType = false;
		setTimeout(() => {
			var args = plus.runtime.arguments;

			var parameter = args.split("//");
			if (args) {
				if (!ifLoginFun()) {
					return;
				}
				uni.navigateTo({
					url: parameter[1],
				});
			}
		}, 10);

		// #endif
	},
	onHide: function () {
		console.log("App Hide");
		if (uni.getSystemInfoSync().platform == "android") {
			this.wakeLock();
		} else {
			Vue.prototype.$hideType = true;
		}
	},
	methods: {
		async checkPerm() {
			const that = this;
			const platform = uni.getSystemInfoSync().platform;
			const { gps, bluetooth, userLocation, userBluetooth } = await this.$store.dispatch("bleManage/checkPermission");
			this.$store.dispatch("bleManage/changeAuthCheckInterrupt", false);

			if (platform === "android" && !gps && this.need2Tip.gps) {
				this.$store.dispatch("bleManage/changeAuthCheckInterrupt", true);
				uni.showModal({
					title: "位置信息权限",
					content: "Android设备使用蓝牙需要开启位置信息功能, 请允许",
					confirmText: "去开启",
					cancelText: "暂不开启",
					success: function (res) {
						if (res.confirm) {
							that.$store.dispatch("bleManage/intoSystemLocationSetting");
						} else if (res.cancel) {
							that.need2Tip.gps = false;
						}
					},
				});
			} else if (!bluetooth && this.need2Tip.bluetooth) {
				this.$store.dispatch("bleManage/changeAuthCheckInterrupt", true);
				uni.showModal({
					title: "蓝牙权限",
					content: "APP需要使用开启系统蓝牙功能, 请允许",
					confirmText: "去开启",
					cancelText: "暂不开启",
					success: function (res) {
						if (res.confirm) {
							that.$store.dispatch("bleManage/intoSystemBluetoothSetting");
						} else if (res.cancel) {
							that.need2Tip.bluetooth = false;
						}
					},
				});
			} else if ((!userLocation || !userBluetooth) && this.need2Tip.user) {
				this.$store.dispatch("bleManage/changeAuthCheckInterrupt", true);
				let title = "",
					content = "";
				if (platform === "android") {
					title = !userLocation ? "位置应用权限" : "蓝牙应用权限";
					content = !userLocation ? "APP需要开启位置应用权限, 请允许" : "APP需要开启扫码附近设备权限, 请允许";
				} else {
					title = "蓝牙应用权限";
					content = "APP需要开启蓝牙应用权限, 请允许";
				}
				uni.showModal({
					title,
					content,
					confirmText: "去开启",
					cancelText: "暂不开启",
					success: function (res) {
						if (res.confirm) {
							that.$store.dispatch("bleManage/intoAppBluetoothSetting");
						} else if (res.cancel) {
							that.need2Tip.user = false;
						}
					},
				});
			}
		},
		// 安卓保洁服务
		/**
		 * 该方法用于在Android平台上获取唤醒锁，以保持应用在后台运行时防止系统进入睡眠状态。
		 * 这对于需要长时间运行的任务（如下载、同步数据等）非常有用。
		 */
		wakeLock() {
			// 获取当前活动的主实例
			var main = plus.android.runtimeMainActivity();
			// 导入Android Context类，用于访问系统服务
			var Context = plus.android.importClass("android.content.Context");
			// 导入Android PowerManager类，用于管理电源状态
			var PowerManager = plus.android.importClass("android.os.PowerManager");
			// 获取PowerManager服务
			var pm = main.getSystemService(Context.POWER_SERVICE);
			// 创建唤醒锁对象，PARTIAL_WAKE_LOCK保持CPU运行，"ANY_NAME"是唤醒锁的标识
			this.g_wakelock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "ANY_NAME");
			// 获取唤醒锁，以防止系统进入睡眠状态
			this.g_wakelock.acquire();
		},
	},
};
</script>

<style lang="scss">
/*每个页面公共css */

/* uview ui */
@import "@/uni_modules/uview-ui/index.scss";

page {
	height: 100%;
	// background-color: #000000;
  background-image: url('@/static/bg/app-background.png'); /* 背景图路径 */
  background-size: cover; /* 覆盖整个页面 */
  background-position: center; /* 居中显示 */
  background-repeat: no-repeat; /* 不重复 */
  background-attachment: fixed; /* 固定背景，不随内容滚动 */
  position: relative; /* 确保子元素定位正常 */
  z-index: 0; /* 设置较低的层级，让内容覆盖背景 */
	max-width: 750px;
	margin: auto;
}

.uni-page-head {
	max-width: 750px;
	margin: auto;
}

.box-pading {
	padding: 0 40rpx;
}

.flex-no-horizontal {
	display: flex;
	align-items: center;
}

.between {
	justify-content: space-between;
}

.p-20 {
	padding: 40rpx;
}

.bold {
	font-weight: bold;
}

.p-20 {
	padding: 40rpx;
}

.p-row-20 {
	padding: 0 40rpx;
}

.p-row-5 {
	padding: 0 10rpx;
}

.m-r-5 {
	margin-right: 10rpx;
}

.m-t-5 {
	margin-top: 10rpx;
}

.m-b-5 {
	margin-bottom: 10rpx;
}

.m-t-10 {
	margin-top: 20rpx;
}

.m-b-10 {
	margin-bottom: 20rpx;
}

.m-r-10 {
	margin-right: 20rpx;
}

.m-b-15 {
	margin-bottom: 30rpx;
}

.m-t-15 {
	margin-top: 30rpx;
}

.m-t-20 {
	margin-top: 40rpx;
}

.m-b-20 {
	margin-bottom: 40rpx;
}

.m-t-30 {
	margin-top: 60rpx;
}

.m-b-30 {
	margin-bottom: 60rpx;
}

.bold {
	font-weight: bold;
}

.f-10 {
	font-size: 10px;
}

.f-xxs {
	font-size: 11px;
}

.f-xs {
	font-size: $uni-font-size-sm;
}

.f-s {
	font-size: $uni-font-size-s;
}

.f-base {
	font-size: $uni-font-size-base;
}

.f-15 {
	font-size: 15px;
}

.f-large {
	font-size: $uni-font-size-lg;
}

.f-xl {
	font-size: $uni-font-size-xlg;
}

.border-box {
	box-sizing: border-box;
}

.full-height {
	height: 100%;
}

.text-center {
	text-align: center;
}

.text-right {
	text-align: right;
}
</style>
